package com.hwg.shiliupro.utils;

import com.hwg.shiliupro.exception.Exception403;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

//接口权限工具类
@Slf4j
public class AuthorityUtils {
    /**
     * key: 用户id     value：用户所拥有的的权限
     */
    private static Map<String, Collection<String>> authoritiesMap = new HashMap<>();

    /**
     * 设置权限(给成员变量authoritiesMap 设置权限    否则后续的校验无法进行)
     * @param uId         你id
     * @param authorities 当局
     */
    public static void setAuthorities(String uId, Collection<String> authorities){
        authoritiesMap.put(uId,authorities);
        log.info("当前用户登录后，设置的权限为：{}",authoritiesMap);
    }

    /**
     * 校验用户是否拥有该权限 (直接根据成员变量里的 权限集合判断 是否包含当前要执行的权限 )
     * @param uId       你id
     * @param authority 权威
     * @return {@link Boolean}
     */
    public static Boolean verify(String uId,String authority){
        if(authoritiesMap.isEmpty()){
            throw new Exception403(403,"您暂无此权限");
        }
        return authoritiesMap.get(uId).contains(authority);    //包含返回true
    }

    /**
     * 判空 判断是否有权限
     * @param uId 你id
     * @return {@link Boolean}
     */
    public static Boolean isEmpty(String uId){
        return ObjectUtils.isEmpty(authoritiesMap.get(uId));
    }

    /**
     * 清空权限集合
     */
    public static void clear(){
        authoritiesMap.clear();
    }
}
